import axios from "axios"
import { Message, Loading } from 'element-ui'
import router from './router'

let loading;
function startLoading() {
    loading = Loading.service({
        lock: true,
        text: '拼命加载中...',
        background: "rgba(0,0,0,0.7)"
    });
}
function endLoading() {
    loading.close();
}
//请求拦截
axios.interceptors.request.use(config => {
    //加载动画
    startLoading();

    if (localStorage.userToken) {
        //配置同意请求头header
        config.headers.Authorization = localStorage.userToken
    }


    return config;
}, error => {
    return Promise.reject(error);
}
)
//响应拦截
axios.interceptors.response.use(response => {
    //结束加载动画
    endLoading();
    return response;
}, error => {
    //错误提醒
    endLoading();
    Message.error(error.response.data);

    //获取错误状态码
    const {status} = error.response;
    if (status == 401) {
        Message.error("token失效,请重新输入")
        //清除token
        localStorage.removeItem("userToken")
        //跳转到登录页面
        router.push("/login")
    }

    return Promise.reject(error)
}
)
//请求拦截
// axios.interceptors.request.use(config => {
//     //加载动画
//     startLoading();
//     return config;
// }, error => {
//     return Promise.reject(error);
// }
// )
//响应拦截
// axios.interceptors.response.use(response => {
//     if (response.data.status == 400 || response.data.message == '邮箱已被注册') {
//         router.push({
//             path: "/",
//             querry: { redirect: router.currentRoute.fullPath }//从哪个页面跳转
//           })
//     }
//     return response;
// },error => {
//     return Promise.reject(error);
// }
// )

export default axios